#include "qhttptest.h"
#include "ui_qhttptest.h"

QHttpTest::QHttpTest(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::QHttpTest)
{
    ui->setupUi(this);

    ui->progressBar->setValue(0);
    ui->progressBar->setMinimum(0);

    // 加载CSS样式
    QFile file;
    file.setFileName(":/new/prefix1/qthttpcss.css");
    file.open(QIODevice::ReadOnly);
    QString strCss = file.readAll();
    this->setStyleSheet(strCss);


    ui->comboBox_PictureType->addItem("JPG");
    ui->comboBox_PictureType->addItem("PNG");
    ui->comboBox_PictureType->addItem("ZIP");
    ui->comboBox_PictureType->addItem("MP3");
    ui->comboBox_PictureType->addItem("MP4");

}

QHttpTest::~QHttpTest()
{
    delete ui;
}

void QHttpTest::on_btnDownload_clicked()
{
    QString strUrl = ui->lineEdit->text().trimmed();
    ui->lineEdit->clear();

    QUrl url = QUrl::fromUserInput(strUrl);
    if(!url.isValid())
    {
        QMessageBox::warning(this,"提示","请输入有效网址");
        return;
    }

    int nIndex = ui->comboBox_PictureType->currentIndex();
    QString fileName = m_filePath + "/"  + url.fileName() + "." + ui->comboBox_PictureType->itemText(nIndex).toLower();
    ui->plainTextEdit->appendPlainText(fileName);

    m_file.setFileName(fileName);
    if(m_file.exists())
    {
        m_file.remove();
    }

    if(m_file.open(QIODevice::WriteOnly))
    {
        QNetworkRequest request(url);
        m_pReply = m_mgr.get(request);

        connect(m_pReply,&QNetworkReply::downloadProgress,this,&QHttpTest::on_downloadProgress);
        connect(m_pReply,&QNetworkReply::finished,this,&QHttpTest::on_finished);
        connect(m_pReply,&QNetworkReply::readyRead,this,&QHttpTest::on_readyRead);

        if(m_pReply->error() == QNetworkReply::NoError)
        {
            ui->btnDownload->setEnabled(false);
        }
        else
        {
            QMessageBox::warning(this,"提示","请求失败");
            return;
        }
    }
    else
    {
        QMessageBox::warning(this,"提示","打开文件失败");
        return;
    }
}


void QHttpTest::on_btnSave_clicked()
{
    m_filePath = QFileDialog::getExistingDirectory(this, "选择保存路径",
                                                   QString(),QFileDialog::ShowDirsOnly|QFileDialog::DontResolveSymlinks);
    if(m_filePath.isEmpty())
    {
        QMessageBox::warning(this,"提示","请选择文件路径");
        return;
    }

    qDebug() << "当前选择的路径" << m_filePath;
    ui->plainTextEdit->appendPlainText(m_filePath);

}


void QHttpTest::on_btnClose_clicked()
{
    this->close();
}

void QHttpTest::on_downloadProgress(qint64 byteReceive,qint64 byteTotal)
{
    ui->progressBar->setMaximum(byteTotal/1024);
    ui->progressBar->setValue(byteReceive/1024);
    qDebug() << "Cur Len"<< byteReceive;

}

void QHttpTest::on_finished()
{
    ui->btnDownload->setEnabled(true);
    m_file.close();
    m_pReply->deleteLater();
    ui->plainTextEdit->appendPlainText("下载完成");
}

void QHttpTest::on_readyRead()
{
    m_file.write(m_pReply->readAll());
}

